package com.seckillpro.seckill_pro.config;


import com.seckillpro.seckill_pro.pojo.TUser;
import com.seckillpro.seckill_pro.service.ITUserService;
import com.seckillpro.seckill_pro.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Package: com.seckillpro.secsill_pro.config
 * @ClassName: UserArgumentResolver
 * @Author: lyx
 * @CreateTime: 2021/3/5 13:34
 * @Description: 自定义用户参数
 */

@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private ITUserService userService;


    //条件的判断,判断参数类型是不是用户， 如果是就执行下面方法
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> parameterType = methodParameter.getParameterType();
        return TUser.class == parameterType;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory)   {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        String ticket = CookieUtil.getCookieValue(request, "tUserTicket");

        if (ticket == null) {
            return null;
        }

        return userService.getUserByCookie(ticket, request, response);
    }
}
